package com.myxml;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
import java.io.FileWriter;

public class XmlModifier {
    public static void main(String[] args) {
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read("book.xml");
            
            // 1. 修改Java核心技术价格
            Element javaBook = (Element) document.selectSingleNode("//book[title='Java核心技术 卷I']");
            if (javaBook != null) {
                Element priceElement = javaBook.element("price");
                priceElement.setText("109.00");  // 更新价格
                javaBook.addAttribute("discount", "true");  // 添加新属性
            }
            
            // 2. 添加新书籍
            Element bookstore = document.getRootElement();
            Element newBook = bookstore.addElement("book")
                .addAttribute("id", "b104")
                .addAttribute("category", "数据库");
            
            newBook.addElement("title").addAttribute("lang", "zh")
                   .addText("SQL必知必会");
            newBook.addElement("author").addText("Ben Forta");
            newBook.addElement("year").addText("2023");
            newBook.addElement("price").addText("65.00");
            
            // 3. 删除算法导论
            Element algoBook = (Element) document.selectSingleNode("//book[@id='b102']");
            if (algoBook != null) {
                bookstore.remove(algoBook);
            }
            
            // 4. 保存修改
            OutputFormat format = OutputFormat.createPrettyPrint();
            XMLWriter writer = new XMLWriter(new FileWriter("updated_books.xml"), format);
            writer.write(document);
            writer.close();
            
            System.out.println("XML修改完成！");
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}